package com.own.component.log.login.core;

import com.own.constant.ConstantCommon;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ExtraLogLoginSpringHook
 *
 * @author chenxueli
 * @date 2022-09-12 13:29:00
 */
@Slf4j
@Component
public class ExtraLogLoginSpringHook {

    private static final Map<String, List<ExtraLogLoginHook>> CUSTOM_LOG_OPERATION_HOOK_MAP = new HashMap<>(8);
    private static final List<ExtraLogLoginHook> CUSTOM_LOG_OPERATION_HOOK_LIST = new ArrayList<>(8);

    @Resource
    private List<ExtraLogLoginHook> extraLogLoginHookList;

    @PostConstruct
    private void init() {
        extraLogLoginHookList.forEach(hook -> {
            var type = hook.clientType();
            if (!ConstantCommon.NONE.equals(hook.name())) {
                if (StringUtils.isBlank(type)) {
                    CUSTOM_LOG_OPERATION_HOOK_LIST.add(hook);
                } else {
                    CUSTOM_LOG_OPERATION_HOOK_MAP.computeIfAbsent(type, k -> new ArrayList<>()).add(hook);
                }
                log.info("自定义登录日志扩展信息接口===>【{}:{}】完成注册", type, hook.name());
            }
        });
    }

    /**
     * 获取对应的日志操作接口
     *
     * @param type 类型
     * @return 日志操作接口
     */
    public List<ExtraLogLoginHook> get(String type) {
        return CUSTOM_LOG_OPERATION_HOOK_MAP.getOrDefault(type, new ArrayList<>());
    }

    /**
     * 获取日志的采集信息
     *
     * @param type 类型
     * @return 采集信息
     */
    public Map<String, Object> collect(String type) {
        var list = get(type);
        var map = new HashMap<String, Object>();
        list.forEach(hook -> map.put(hook.name(), hook.collect()));
        CUSTOM_LOG_OPERATION_HOOK_LIST.forEach(hook -> map.put(hook.name(), hook.collect()));
        return map;
    }

}
